package com.enba.mallapi.config;

import com.enba.mallapi.config.LongToStringSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Configuration
public class JacksonConfig {

  // 定义日期时间格式，按需调整，比如："yyyy-MM-dd HH:mm:ss"
  private static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

  @Bean
  public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
    // Java 8 日期时间模块，支持 LocalDateTime 等
    JavaTimeModule javaTimeModule = new JavaTimeModule();

    // 定义 LocalDateTime 的序列化格式（可选）
    javaTimeModule.addSerializer(
        LocalDateTime.class,
        new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATETIME_FORMAT)));

    // 你可以自定义 Long 和 long 的序列化器，防止精度丢失
    SimpleModule longModule = new SimpleModule();
    longModule.addSerializer(Long.class, new LongToStringSerializer());
    longModule.addSerializer(long.class, new LongToStringSerializer());

    // 构建 ObjectMapper 并注册两个模块
    return builder
        .modulesToInstall(javaTimeModule, longModule) // 注册 JavaTimeModule 和你的 LongModule
        .build();
  }
}
